#pragma once

#include <iostream>
#include <mysql/mysql.h>
#include "util.hpp"

namespace easymysql
{
class connection
{
public:
    connection(const std::string& host, const std::string& user, const std::string& passwd, const std::string& db, uint16_t port)
    {
        if ((_conn = mysql_init(nullptr)) == nullptr)
        {
            throw except("mysql init failed");
        }

        if (mysql_real_connect(_conn, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
        {
            mysql_close(_conn);
            throw except(std::string("connect failed: ") + mysql_error(_conn));
        }
    }

    ~connection()
    {
        if (_conn)
            mysql_close(_conn);
    }

    MYSQL* handler() const
    {
        return _conn;
    }

private:
    MYSQL* _conn;
};

} // namespace easymysql
